import Vue from "vue";
import VueRouter from "vue-router";

import Login from "@/views/Login";
import Register from "@/views/Register";
import Detail from "@/views/Detail";
import Layout from "@/views/Layout";

// import Like from "@/views/Like";
// import Article from "@/views/Article";
// import Collect from "@/views/Collect";
// import User from "@/views/User";
const Like = () => import("@/views/Like");
const Article = () => import("@/views/Article");
const Collect = () => import("@/views/Collect");
const User = () => import("@/views/User");

// 引入token
import { getToken } from "@/utils/storage";
import { Toast } from "vant";

Vue.use(VueRouter);
const router = new VueRouter({
  routes: [
    {
      path: "/",
      component: Layout,
      redirect: "/article",
      children: [
        { path: "article", component: Article },
        { path: "like", component: Like },
        { path: "collect", component: Collect },
        { path: "user", component: User },
      ],
    },
    { path: "/login", component: Login },
    { path: "/register", component: Register },
    { path: "/detail/:id", component: Detail },
  ],
});

// 白名单，不需要token就可以访问的页面，例如登录注册
const whiteList = ["/login", "/register"];
router.beforeEach((to, form, next) => {
  // console.log(to.path);
  // console.log(whiteList.includes(to.path));
  const token = getToken();
  if (token || whiteList.includes(to.path)) {
    next();
  } else {
    Toast("请先登录");
    next("/login");
  }
});

export default router;
